<?php

namespace backend\module\content\controllers;

use Yii;
use backend\module\content\models\Article;
use backend\module\content\models\ArticleSearch;
use backend\module\content\controllers\ContentBaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use backend\module\content\models\ContentCategory;
use backend\components\actions\ChangeValueAction;
use backend\components\actions\BulkMoveAction;
use backend\models\BackendUser;
use backend\components\actions\RegionSelectAction;
/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends ContentBaseController {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return ArrayHelper::merge(parent::behaviors(), [
        ]);
    }

    public function actions() {
        return ArrayHelper::merge(parent::actions(), [
                    'change-value' => [
                        'class' => ChangeValueAction::className(),
                        'modelClass' => Article::className(),
                        'outputValue' => function($model, $attribute, $key, $index) {
                            return $model->$attribute;
                        }
                    ],
                    'bulk-move' => [
                        'class' => BulkMoveAction::className(),
                        'modelClass' => Article::className(),
                    ],
                    'region-select' => [
                        'class' => RegionSelectAction::className(),
                    ]
        ]);
    }

    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new ArticleSearch();
        $catid = Yii::$app->request->get('catid');

        $data = ContentCategory::getAllData(BackendUser::getParentUserId());
        $ztreeNode = json_encode(ContentCategory::getZtreeNode($data, $catid));
        $breadcrumb = ContentCategory::getBreadcrumb($data, $catid);
        $ids = ContentCategory::getSubNodeId($data, $catid);
        
        $select2Data = ContentCategory::getSubNodeModel(
                        ContentCategory::getAllData(BackendUser::getParentUserId()),
                        'article'
                    );
        $ids[] = $catid;

        $cateMap = ArrayHelper::map($data, 'id', 'name');
        $searchModel->userid = BackendUser::getParentUserId();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $ids);
        return $this->render('index', [
                    'ztreeNode' => $ztreeNode,
                    'searchModel' => $searchModel,
                    'catid' => Yii::$app->request->get('catid'),
                    'dataProvider' => $dataProvider,
                    'breadcrumb' => $breadcrumb,
                    'select2Data' => $select2Data,
                    'cateMap' => $cateMap,
        ]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {
        $request = Yii::$app->request;
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [
            'title' => Yii::t('common', 'View'),
            'content' => $this->renderAjax('view', [
                'model' => $this->findModel($id),
            ]),
            'footer' => Html::button(Yii::t('common', 'Close'), ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
            Html::a(Yii::t('common', 'Edit'), ['update', 'id' => $id], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
        ];
    }

    /**
     * Creates a new Article model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $request = Yii::$app->request;
        $model = new Article();
        $model->catid = $request->get('catid');
        $model->userid = BackendUser::getParentUserId();
        $model->sort = 100;
        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            return $this->redirect(['index', 'catid' => $model->catid]);
        }
        return $this->render('create', [
                    'model' => $model,
        ]);
    }

    /**
     * Updates an existing Article model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $request = Yii::$app->request;
        $model = $this->findModel($id);

        if ($request->isPost && $model->load($request->post()) && $model->save()) {
            return $this->redirect(['index', 'catid' => $model->catid]);
        }
        $model->created = date('Y-m-d h:i:s', $model->created);
        return $this->render('update', [
                    'model' => $model,
        ]);
    }

    /**
     * Delete an existing Article model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        Yii::$app->response->format = Response::FORMAT_JSON;
        return ['forceClose' => true, 'forceReload' => '#crud-datatable-pjax'];
    }

    /**
     * Delete multiple existing Article model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete() {
        $request = Yii::$app->request;
        $pks = explode(',', $request->post('pks')); // Array or selected records primary keys
        foreach ($pks as $pk) {
            $model = $this->findModel($pk);
            $model->delete();
        }

        Yii::$app->response->format = Response::FORMAT_JSON;
        return ['forceClose' => true, 'forceReload' => '#crud-datatable-container'];
    }
    /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        $userid = BackendUser::getParentUserId();
        if (($model = Article::findOne(['id' => $id, 'userid' => $userid])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * 返回指定分类的AR对象
     * @param int $catid 分类ID
     * @return AR
     */
    protected function getCate($catid) {
        return ContentCategory::findOne($catid);
    }

}
